package my.http;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.app.teadoor.bean.BaseListBeanXF;
import com.app.teadoor.bean.BaseMsgBean;
import com.app.teadoor.bean.BasicBeanStr;
import com.app.teadoor.bean.BasisBean;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import my.LogUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.Response;

class MyHttpResposeHandler implements Callback {
    private static String tag = "HTTP";
    int what = 0;
    MyHttpListener mListener;
    Class<?> clazz;
    ResponderHandler handler;

    public MyHttpResposeHandler(MyHttpListener mListener, int what,
                                Class<?> clazz) {
        super();
        this.what = what;
        this.mListener = mListener;
        this.clazz = clazz;
        handler =  new ResponderHandler(this);
    }

    private static Object parseResoposeBody(String responseBody, Class<?> clazz) {
        if (responseBody == null) return null;
//        String result = new String(responseBody);
        String result = responseBody;
        LogUtil.d(tag, "" + result);
        if (TextUtils.isEmpty(result))
            return null;
        try {
            // result = StringUtil.decodeUnicode(result);
            MyBaseBean bean = JSON.parseObject(result, MyBaseBean.class);

            result = JSON.toJSONString(bean, SerializerFeature.WriteNullStringAsEmpty);
            bean = JSON.parseObject(result, MyBaseBean.class);
//			MyBaseBean bean = JSON.parseObject(result, MyBaseBean.class);
            BasisBean resultBean;
            if (clazz == null) {
                resultBean = new BasisBean();
            } else if (!TextUtils.isEmpty(bean.getResultData())) {

                if (BasicBeanStr.class.isAssignableFrom(clazz)) {
//					JSONObject jsonObject = JSON.parseObject(bean.getResultData());
//					bean.setResultData("{\"msg\":\""+bean.getResultData()+"\"}");
                }else {
                    if (bean.getResultData().startsWith("[")) {
                        if (bean.getResultData().startsWith("[\"")) {
                            bean.setResultData("{\"list\":[]}");
                        } else {
                            bean.setResultData("{\"list\":" + bean.getResultData() + "}");
                        }
                    }
                }
                if (BaseMsgBean.class.isAssignableFrom(clazz)) {
//					JSONObject jsonObject = JSON.parseObject(bean.getResultData());
                    bean.setResultData("{\"msg\":\"" + bean.getResultData() + "\"}");
                }
//
//				 if(!TextUtils.isEmpty(bean.getResultData()) && bean.getResultData().equals("数据为空")) {
//					bean.setResultData("{\"list\":[]}");
//				}

                if (!TextUtils.isEmpty(bean.getResultData()) && !bean.getResultData().startsWith("{")) {
                    resultBean = new BasisBean();
                    bean.setStatusCode(-1);
                } else {

                    resultBean = (BasisBean) JSON.parseObject(
                            bean.getResultData(), clazz);
                }
            } else if (bean.getResultData() == null
                    || bean.getResultData().equals("null")
                    || bean.getResultData().equals("{}")
                    || (bean.getResultData().length() == 0)) {
                resultBean = (BasisBean) clazz.newInstance();
            } else {
                resultBean = (BasisBean) JSON.parseObject(bean.getResultData(),
                        clazz);
            }
//            resultBean.setStatusCode(bean.getStatusCode());
            resultBean.setCode((bean.getCode()));
            resultBean.setStatusInfo(bean.getStatusInfo());
            resultBean.setResultData(bean.getResultData());
            resultBean.setRight(bean.getRight());
            resultBean.setRecordsTotal(bean.getRecordsTotal());
            resultBean.setAttr(bean.getAttr());
            resultBean.setToken(bean.getToken());
            resultBean.setUid(bean.getUid());
            resultBean.setUno(bean.getUno());
            resultBean.setUname(bean.getUname());
            resultBean.setUfsign(bean.getUfsign());
            resultBean.setAid(bean.getAid());
            resultBean.setAname(bean.getAname());
            resultBean.setAcode(bean.getAcode());

            if (BaseListBeanXF.class.isAssignableFrom(clazz)) {
//					JSONObject jsonObject = JSON.parseObject(bean.getResultData());
                ((BaseListBeanXF)resultBean).setCurrent_page(bean.getCurrent());
                ((BaseListBeanXF)resultBean).setLast_page(bean.getTotalPages());
                ((BaseListBeanXF)resultBean).setTotal(bean.getTotal());
                ((BaseListBeanXF)resultBean).setPer_page(bean.getPageSize());
            }
            return resultBean;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        LogUtil.d(tag, "onFailure: " + e.getMessage());
        if (mListener == null)
            return;
        Message msg = new Message();
        msg.obj = null;
        handler.sendMessage(msg);

    }



    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        if (mListener == null)
            return;
        LogUtil.i(tag, "onResponse:"+response.protocol() + " " + response.code() + " " + response.message());
        Headers headers = response.headers();
        for (int i = 0; i < headers.size(); i++) {
//            LogUtil.d(tag, headers.name(i) + ":" + headers.value(i));
        }
        if(response.code() == 403 || response.code() == 401 ){
            BasisBean basisBean = new BasisBean();
            basisBean.setCode(BasisBean.CODE_PAST_1);
            basisBean.setStatusInfo("登录超时，请重新登录");
            Message msg = new Message();
            msg.obj = basisBean;
            handler.sendMessage(msg);
        }else {
            String responseBody = response.body().string();

            Object object = parseResoposeBody(responseBody, clazz);
            Message msg = new Message();
            msg.obj = object;
            handler.sendMessage(msg);
        }

    }

    private static class ResponderHandler extends Handler {
        private final MyHttpResposeHandler mResponder;

        ResponderHandler(MyHttpResposeHandler mResponder) {
            this.mResponder = mResponder;
        }

        @Override
        public void handleMessage(Message msg) {
            Object object = msg.obj;
            if (object == null) {
                mResponder. mListener.onFailure(mResponder.what, null);
                mResponder.mListener.onFinish(mResponder.what);
            } else {
                BasisBean bean = (BasisBean) object;
                if (bean.isCodeOk()) {
                    mResponder. mListener.onSuccess(mResponder.what, object);
                } else {
                    mResponder.mListener.onFailure(mResponder.what, object);
                }
            }
            mResponder.mListener.onFinish(mResponder.what);
        }
    }

}
